package com.itheima.wisdomnext.service.ImpI;

import com.itheima.wisdomnext.entity.Comment;
import com.itheima.wisdomnext.entity.CommentShow;
import com.itheima.wisdomnext.entity.Result.enumcalss.ErrorCode;
import com.itheima.wisdomnext.entity.Users;
import com.itheima.wisdomnext.mapper.CommentMapper;
import com.itheima.wisdomnext.service.CommentService;
import com.itheima.wisdomnext.service.UserService;
import com.itheima.wisdomnext.util.CategoryS_Util;
import com.itheima.wisdomnext.util.CommentS_Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private UserService userService;

    private static final String UPLOAD_DIR = "uploads/comments/";

    /**
     * 获取某个帖子的所有评论（包含用户信息、回复数量、是否点赞等）
     *
     * @param postId 帖子 ID
     * @param userId 当前用户 ID，用于判断是否点赞
     * @return 评论展示列表
     */
    @Override
    public List<CommentShow> getCommentsByPostIdWithDetails(Integer postId, Integer userId) {
        List<Comment> comments = commentMapper.findByPostId(postId);
        if (comments == null || comments.size() == 0) {
            CommentS_Util.isTrue(true, ErrorCode.FAILED,"获取某个帖子的所有评论失败");
        }
        List<CommentShow> commentShows = new ArrayList<>();
        for (Comment comment : comments) {
            CommentShow commentShow = convertToCommentShow(comment, userId);
            commentShows.add(commentShow);
        }
        return commentShows;
    }

    /**
     * 获取某条评论及其所有回复
     *
     * @param commentId 评论 ID
     * @param userId 当前用户 ID
     * @return 评论及其回复的展示对象
     */
    @Override
    public CommentShow getCommentWithReplies(Integer commentId, Integer userId) {
        Comment comment = commentMapper.getCommentById(commentId);
        if (comment == null) {
            CommentS_Util.isTrue(true, ErrorCode.FAILED,"获取某条评论及其所有回复失败");
        }

        CommentShow commentShow = convertToCommentShow(comment, userId);

        List<Comment> replies = commentMapper.findByParentId(commentId);
        if (replies == null) {
            CommentS_Util.isTrue(true, ErrorCode.FAILED,"获取某条评论及其所有回复失败");
        }
        List<CommentShow> replyShows = new ArrayList<>();
        for (Comment reply : replies) {
            CommentShow replyShow = convertToCommentShow(reply, userId);
            replyShows.add(replyShow);
        }

        commentShow.setReplies(replyShows);
        return commentShow;
    }

    /**
     * 将 Comment 转换为 CommentShow，封装详细信息
     */
    private CommentShow convertToCommentShow(Comment comment, Integer userId) {
        CommentShow commentShow = new CommentShow();
        commentShow.setId(comment.getId());
        commentShow.setPostId(comment.getPostId());
        commentShow.setUserId(comment.getUserId());
        commentShow.setContent(comment.getContent());
        commentShow.setParentId(comment.getParentId());
        commentShow.setLikes(comment.getLikes());
        commentShow.setCreatedAt(comment.getCreatedAt());

        // 设置用户信息
        Users user = userService.getUserById(comment.getUserId());
        if (user == null) {
            CommentS_Util.isTrue(true, ErrorCode.FAILED,"设置用户信息失败");
        }
        commentShow.setUser(user);

        // 设置回复数量
        int replyCount = commentMapper.selectReplyCountByCommentId(comment.getId());
        commentShow.setReplyCount(replyCount);

        // 判断是否点赞
        if (userId != null) {
            boolean isLiked = commentMapper.isCommentLikedByUser(comment.getId(), userId) > 0;
            commentShow.setLikedByUser(isLiked);
        }

        return commentShow;
    }

    /**
     * 添加一条评论
     *
     * @param comment 评论实体
     */
    @Override
    public void addComment(Comment comment) throws Exception{
        commentMapper.insertComment(comment);
    }

    /**
     * 上传评论附带的图片（预留方法，未实际使用）
     *
     * @param file 图片文件
     * @return 图片路径
     */
    private String uploadFile(MultipartFile file) throws Exception{
        if (file == null) CommentS_Util.isTrue(true, ErrorCode.FAILED,"file为bull");;
            File directory = new File(UPLOAD_DIR);
            if (!directory.exists()) {
                directory.mkdirs();
            }

            String originalFilename = file.getOriginalFilename();
            String newFilename = System.currentTimeMillis() + "_" + originalFilename;
            Path path = Paths.get(UPLOAD_DIR + newFilename);
            Files.copy(file.getInputStream(), path);
            return "/uploads/comments/" + newFilename;
    }

    /**
     * 更新评论内容
     *
     * @param comment 评论对象
     * @return 更新后的评论对象
     */
    @Override
    public Comment updateComment(Comment comment) throws Exception{
        commentMapper.updateComment(comment);
        return comment;
    }

    /**
     * 删除评论
     *
     * @param id 评论 ID
     */
    @Override
    public void deleteComment(Integer id) throws Exception{
        commentMapper.deleteComment(id);
    }

    /**
     * 获取指定评论的回复数量
     *
     * @param commentId 评论 ID
     * @return 回复数量
     */
    @Override
    public int getReplyCountByCommentId(Integer commentId) throws Exception{
        return commentMapper.selectReplyCountByCommentId(commentId);
    }

    /**
     * 判断用户是否点赞了某条评论
     *
     * @param commentId 评论 ID
     * @param userId 用户 ID
     * @return true 表示已点赞，false 表示未点赞
     */
    @Override
    public boolean isCommentLikedByUser(Integer commentId, Integer userId) throws Exception{
        int count = commentMapper.isCommentLikedByUser(commentId, userId);
        return count > 0;
    }
}
